<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>面向对象思想 | 夜悊的技术小宅</title><meta name="author" content="夜悊"><meta name="copyright" content="夜悊"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="前言学习设计模式，需要了解面向对象思想。利用面向对象思想的特性，能够帮助我们设计出优秀的程序。  面向过程思想特点 关注点：正在发生的过程 事情的发生按照一定的“逻辑时间顺序” 符合多数人思考、计算机处理问题的逻辑  示例（C++语言描述）12345678910111213141516171819202122232425262728#include &lt;iostream&gt;using na">
<meta property="og:type" content="article">
<meta property="og:title" content="面向对象思想">
<meta property="og:url" content="http://example.com/2022/04/15/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3/index.html">
<meta property="og:site_name" content="夜悊的技术小宅">
<meta property="og:description" content="前言学习设计模式，需要了解面向对象思想。利用面向对象思想的特性，能够帮助我们设计出优秀的程序。  面向过程思想特点 关注点：正在发生的过程 事情的发生按照一定的“逻辑时间顺序” 符合多数人思考、计算机处理问题的逻辑  示例（C++语言描述）12345678910111213141516171819202122232425262728#include &lt;iostream&gt;using na">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/img/cover4.png">
<meta property="article:published_time" content="2022-04-14T17:23:54.000Z">
<meta property="article:modified_time" content="2023-04-11T13:05:24.690Z">
<meta property="article:author" content="夜悊">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/img/cover4.png"><link rel="shortcut icon" href="/img/favicon2.png"><link rel="canonical" href="http://example.com/2022/04/15/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css?v=4.13.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.1/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0.33/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: 夜悊","link":"链接: ","source":"来源: 夜悊的技术小宅","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid@4.11.1/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '面向对象思想',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-04-11 21:05:24'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="/css/my_css.css"><meta name="generator" content="Hexo 7.3.0"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">92</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">15</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 笔记目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-blog"></i><span> 其他博客</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/m0_62083249"><i class="fa-fw fa fa-link"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/ye-zhe-ning"><i class="fa-fw fa fa-link"></i><span> 知乎</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-sitemap"></i><span> 代码仓库</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://gitee.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Gitee</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://github.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Github</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about_me/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/cover4.png')"><nav id="nav"><span id="blog-info"><a href="/" title="夜悊的技术小宅"><span class="site-name">夜悊的技术小宅</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-bookmark"></i><span> 笔记目录</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-blog"></i><span> 其他博客</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/m0_62083249"><i class="fa-fw fa fa-link"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/ye-zhe-ning"><i class="fa-fw fa fa-link"></i><span> 知乎</span></a></li></ul></div><div class="menus_item"><a class="site-page group hide" href="javascript:void(0);"><i class="fa-fw fa fa-sitemap"></i><span> 代码仓库</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://gitee.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Gitee</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://github.com/yezhening"><i class="fa-fw fa fa-link"></i><span> Github</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about_me/"><i class="fa-fw fas fa-user"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">面向对象思想</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-04-14T17:23:54.000Z" title="发表于 2022-04-15 01:23:54">2022-04-15</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-04-11T13:05:24.690Z" title="更新于 2023-04-11 21:05:24">2023-04-11</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="面向对象思想"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>学习设计模式，需要了解面向对象思想。利用面向对象思想的特性，能够帮助我们设计出优秀的程序。</p>
<hr>
<h1 id="面向过程思想"><a href="#面向过程思想" class="headerlink" title="面向过程思想"></a>面向过程思想</h1><h2 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h2><ul>
<li>关注点：正在发生的过程</li>
<li>事情的发生按照一定的“逻辑时间顺序”</li>
<li>符合多数人思考、计算机处理问题的逻辑</li>
</ul>
<h2 id="示例（C-语言描述）"><a href="#示例（C-语言描述）" class="headerlink" title="示例（C++语言描述）"></a>示例（C++语言描述）</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//定义并初始化变量</span></span><br><span class="line">    <span class="type">int</span> num1 = <span class="number">1</span>;	<span class="comment">//操作数1</span></span><br><span class="line">    <span class="type">char</span> oper = <span class="string">&#x27;+&#x27;</span>;	<span class="comment">//计算符</span></span><br><span class="line">    <span class="type">int</span> num2 = <span class="number">2</span>;	<span class="comment">//操作数2</span></span><br><span class="line">    <span class="type">int</span> result = <span class="number">0</span>;	<span class="comment">//计算结果</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">//判定并计算</span></span><br><span class="line">    <span class="keyword">switch</span> (oper)</span><br><span class="line">    &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;+&#x27;</span>:</span><br><span class="line">        result = num1 + num2;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;-&#x27;</span>:</span><br><span class="line">        result = num1 - num2;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    cout &lt;&lt; result &lt;&lt; endl;	<span class="comment">//输出计算结果</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序<strong>先</strong>定义并初始化变量，<strong>然后</strong>进行判断计算，<strong>最后</strong>输出结果。程序的执行“从上至下”（按照语句顺序），“从过去到未来”（按照时间顺序）经历一定的过程。</p>
<h2 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h2><ul>
<li>维护性差</li>
<li>复用性差</li>
<li>扩展性差</li>
<li>灵活性差</li>
</ul>
<hr>
<h1 id="优秀程序设计的四个特性"><a href="#优秀程序设计的四个特性" class="headerlink" title="优秀程序设计的四个特性"></a>优秀程序设计的四个特性</h1><p>在实际业务、服务开发中，需求变化，程序就要修改。<strong>优秀程序设计旨在用更短的时间、变动更少的代码、按一定设计步骤有序无差错地完成任务。</strong></p>
<ul>
<li>维护性：只修改相关代码&#x2F;功能，而不影响其他代码&#x2F;功能</li>
<li>复用性：代码&#x2F;功能可重复使用</li>
<li>扩展性：能在原有代码&#x2F;功能基础上，增添新的代码&#x2F;功能</li>
<li>灵活性：代码&#x2F;功能适用于多种场景</li>
</ul>
<hr>
<h1 id="面向对象思想"><a href="#面向对象思想" class="headerlink" title="面向对象思想"></a>面向对象思想</h1><p>关注点：正在受影响的对象<br>三大特性：封装，继承，多态</p>
<h2 id="封装"><a href="#封装" class="headerlink" title="封装"></a>封装</h2><p>目的</p>
<ul>
<li>拆分逻辑</li>
<li>降低耦合度</li>
<li>隐藏实现细节</li>
<li>…</li>
</ul>
<p>示例（C++语言描述）</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="comment">//计算类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operation</span>	</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="type">int</span> num1;	<span class="comment">//操作数1</span></span><br><span class="line">    <span class="type">char</span> oper;	<span class="comment">//计算符</span></span><br><span class="line">    <span class="type">int</span> num2;	<span class="comment">//操作数2</span></span><br><span class="line">    <span class="type">int</span> result;	<span class="comment">//计算结果</span></span><br><span class="line"></span><br><span class="line">	<span class="comment">//计算方式</span></span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">calculate</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">switch</span> (oper)</span><br><span class="line">        &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;+&#x27;</span>:</span><br><span class="line">            result = num1 + num2;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;-&#x27;</span>:</span><br><span class="line">            result = num1 - num2;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//创建并初始化计算类的对象</span></span><br><span class="line">    Operation operation;	</span><br><span class="line">    operation.num1 = <span class="number">1</span>;</span><br><span class="line">    operation.oper = <span class="string">&#x27;+&#x27;</span>;</span><br><span class="line">    operation.num2 = <span class="number">2</span>;</span><br><span class="line">    </span><br><span class="line">    operation.<span class="built_in">calculate</span>();	<span class="comment">//计算</span></span><br><span class="line"></span><br><span class="line">    cout &lt;&lt; operation.result &lt;&lt; endl;	<span class="comment">//输出计算结果</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序定义了一个计算类，将”操作数、操作符、计算结果和计算方式”逻辑相似且共同实现一种功能的“实体”<strong>封装</strong>；在主函数中将计算的业务逻辑和输出显示的界面的代码<strong>逻辑拆分</strong>，修改代码可选择只修改其中一部分而不影响另一部分，<strong>耦合度降低</strong>；对主函数而言，计算类的<strong>实现细节是隐藏的</strong>，主函数只需知道如何调用，可以将计算类<strong>复用</strong>在其他位置。</p>
<h2 id="继承和多态"><a href="#继承和多态" class="headerlink" title="继承和多态"></a>继承和多态</h2><p>目的</p>
<ul>
<li>拆分逻辑</li>
<li>降低耦合度</li>
<li>…</li>
</ul>
<p>当需要修改计算类时，仍然存在耦合度高的问题。例如想为其增添“乘法计算”功能，则需在“calculate()”函数的“switch”语句中添加代码，可能会错误修改“加法、减法计算”功能的代码。</p>
<p>示例（C++语言描述）</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="comment">//计算类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operation</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="type">int</span> num1;   <span class="comment">//操作数1</span></span><br><span class="line">    <span class="type">char</span> oper;  <span class="comment">//计算符</span></span><br><span class="line">    <span class="type">int</span> num2;   <span class="comment">//操作数2</span></span><br><span class="line">    <span class="type">int</span> result; <span class="comment">//计算结果</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">virtual</span> <span class="type">void</span> <span class="title">calculate</span><span class="params">()</span> </span>= <span class="number">0</span>; <span class="comment">//纯虚函数</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//计算加法类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operation_add</span> : <span class="keyword">public</span> Operation <span class="comment">//继承</span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">calculate</span><span class="params">()</span> <span class="comment">//重载  多态</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        result = num1 + num2;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//计算减法类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operation_sub</span> : <span class="keyword">public</span> Operation</span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">calculate</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        result = num1 - num2;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//计算乘法类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operation_mul</span> : <span class="keyword">public</span> Operation</span><br><span class="line">&#123;</span><br><span class="line">    <span class="function"><span class="type">void</span> <span class="title">calculate</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        result = num1 * num2;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 程序设计思路：依据给定的计算符，创建计算类相应的子类对象，调用子类的方法计算</span></span><br><span class="line"><span class="comment"> * 使用简单工厂模式</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">//计算工厂类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Operation_factory</span></span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="type">static</span> Operation *<span class="title">create_operation</span><span class="params">(<span class="type">char</span> oper)</span> <span class="comment">//静态函数</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        Operation *operation = <span class="literal">NULL</span>; <span class="comment">//指向计算类的指针</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//依据给定的计算符，创建计算类相应的子类</span></span><br><span class="line">        <span class="keyword">switch</span> (oper)</span><br><span class="line">        &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;+&#x27;</span>:</span><br><span class="line">            operation = <span class="keyword">new</span> <span class="built_in">Operation_add</span>();</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;-&#x27;</span>:</span><br><span class="line">            operation = <span class="keyword">new</span> <span class="built_in">Operation_sub</span>();</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">&#x27;*&#x27;</span>:</span><br><span class="line">            operation = <span class="keyword">new</span> <span class="built_in">Operation_mul</span>();</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> operation;	<span class="comment">//返回相应的计算子类对象</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">	<span class="comment">//依据给定的计算符，创建计算类相应的子类对象并初始化</span></span><br><span class="line">    Operation *operation = Operation_factory::<span class="built_in">create_operation</span>(<span class="string">&#x27;+&#x27;</span>);	</span><br><span class="line">    <span class="comment">//静态函数属于类而不是对象，由类直接调用</span></span><br><span class="line">    operation-&gt;num1 = <span class="number">1</span>;</span><br><span class="line">    operation-&gt;num2 = <span class="number">2</span>;</span><br><span class="line">    </span><br><span class="line">    operation-&gt;<span class="built_in">calculate</span>();	<span class="comment">//计算</span></span><br><span class="line"></span><br><span class="line">    cout &lt;&lt; operation-&gt;result &lt;&lt; endl;	<span class="comment">//输出计算结果</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过<strong>继承</strong>，将“计算”的各个“子功能”<strong>逻辑拆分</strong>，每个功能单独成一“类”，<strong>耦合度降低</strong>；通过<strong>多态</strong>，将函数重载以实现不同的计算。当再想增加一个“除法计算”功能时，只需增加一个计算除法子类，并在计算工厂类的“switch”语句中增加一个创建计算除法子类对象的分支，而不会“触碰”&#x2F;误修改到“加、减和乘法计算”功能的代码，提高了程序的<strong>维护性</strong>。</p>
<hr>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><ul>
<li>面向过程的关注点：正在发生的过程</li>
<li>优秀程序设计的四大特性：维护性，复用性，扩展性，灵活性</li>
<li>面向对象的关注点：正在受影响的对象</li>
<li>三大特性：封装，继承，多态</li>
</ul>
<hr>
<h1 id="作者的话"><a href="#作者的话" class="headerlink" title="作者的话"></a>作者的话</h1><ul>
<li>文章内容基于读者有一定程序设计基础，了解面向过程、对象思想等一定知识，主要目的是对知识的串讲、延拓，详细概念理解请参阅其他资料</li>
<li>文章内容示例简单，思想优越性的体现可能不理想。当拓展到大型业务、服务和程序时，务须具备高效的设计思想、使用良好的设计模式编程</li>
<li>文章在描述时有疑惑的地方，请留言，必会一一耐心讨论、解答</li>
<li>文章在认识上有错误的地方, 敬请批评指正</li>
<li>望读者们都能有所收获</li>
</ul>
<hr>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><p>《大话设计模式》作者：程杰</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="http://example.com">夜悊</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2022/04/15/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3/">http://example.com/2022/04/15/面向对象思想/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">夜悊的技术小宅</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a></div><div class="post_share"><div class="social-share" data-image="/img/cover4.png" data-sites="qq,wechat,weibo"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1.1.3/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1.1.3/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/2022/04/16/IRC%EF%BC%88Internet%20Relay%20Chat%EF%BC%89%EF%BC%88%E5%9B%A0%E7%89%B9%E7%BD%91%E4%B8%AD%E7%BB%A7%E8%81%8A%E5%A4%A9%EF%BC%89%E5%8D%8F%E8%AE%AE%E2%80%94%E2%80%94RFC1459%E6%96%87%E6%A1%A3%E8%A6%81%E7%82%B9%E6%80%BB%E7%BB%93/" title="IRC（Internet Relay Chat）（因特网中继聊天）协议——RFC1459文档要点总结"><img class="cover" src= "" data-lazy-src="/img/cover4.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">IRC（Internet Relay Chat）（因特网中继聊天）协议——RFC1459文档要点总结</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/12/25/%E4%B8%AD%E4%BB%8B%E8%80%85%E5%92%8C%E8%AE%BF%E9%97%AE%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88%E8%A1%8C%E4%B8%BA%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E7%9A%84%20C++%20%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%E6%A8%A1%E6%9D%BF/" title="中介者和访问者模式（行为型设计模式）的 C++ 代码示例模板"><img class="cover" src= "" data-lazy-src="/img/cover19.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-25</div><div class="title">中介者和访问者模式（行为型设计模式）的 C++ 代码示例模板</div></div></a></div><div><a href="/2022/08/09/%E5%88%9B%E5%BB%BA%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E6%80%BB%E7%BB%93/" title="创建型设计模式总结"><img class="cover" src= "" data-lazy-src="/img/cover10.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-09</div><div class="title">创建型设计模式总结</div></div></a></div><div><a href="/2023/12/19/%E4%BB%A3%E7%90%86%E5%92%8C%E9%80%82%E9%85%8D%E5%99%A8%E6%A8%A1%E5%BC%8F%EF%BC%88%E7%BB%93%E6%9E%84%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E7%9A%84%20C++%20%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%E6%A8%A1%E6%9D%BF/" title="代理和适配器模式（结构型设计模式）的 C++ 代码示例模板"><img class="cover" src= "" data-lazy-src="/img/cover14.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-19</div><div class="title">代理和适配器模式（结构型设计模式）的 C++ 代码示例模板</div></div></a></div><div><a href="/2023/11/21/%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%88%9B%E5%BB%BA%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E7%9A%84%20C++%20%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%E6%A8%A1%E6%9D%BF/" title="单例模式（创建型设计模式）的 C++ 代码示例模板"><img class="cover" src= "" data-lazy-src="/img/cover6.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-11-21</div><div class="title">单例模式（创建型设计模式）的 C++ 代码示例模板</div></div></a></div><div><a href="/2023/11/20/%E5%8E%9F%E5%9E%8B%E5%92%8C%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%88%9B%E5%BB%BA%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E7%9A%84%20C++%20%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%E6%A8%A1%E6%9D%BF/" title="原型和建造者模式（创建型设计模式）的 C++ 代码示例模板"><img class="cover" src= "" data-lazy-src="/img/cover19.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-11-20</div><div class="title">原型和建造者模式（创建型设计模式）的 C++ 代码示例模板</div></div></a></div><div><a href="/2023/12/20/%E5%A4%96%E8%A7%82%E3%80%81%E8%A3%85%E9%A5%B0%E5%92%8C%E7%BB%84%E5%90%88%E6%A8%A1%E5%BC%8F%EF%BC%88%E7%BB%93%E6%9E%84%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E7%9A%84%20C++%20%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B%E6%A8%A1%E6%9D%BF%E3%80%82/" title="外观、装饰和组合模式（结构型设计模式）的 C++ 代码示例模板"><img class="cover" src= "" data-lazy-src="/img/cover9.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-20</div><div class="title">外观、装饰和组合模式（结构型设计模式）的 C++ 代码示例模板</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E8%BF%87%E7%A8%8B%E6%80%9D%E6%83%B3"><span class="toc-number">2.</span> <span class="toc-text">面向过程思想</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%89%B9%E7%82%B9"><span class="toc-number">2.1.</span> <span class="toc-text">特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%A4%BA%E4%BE%8B%EF%BC%88C-%E8%AF%AD%E8%A8%80%E6%8F%8F%E8%BF%B0%EF%BC%89"><span class="toc-number">2.2.</span> <span class="toc-text">示例（C++语言描述）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%BA%E7%82%B9"><span class="toc-number">2.3.</span> <span class="toc-text">缺点</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BC%98%E7%A7%80%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%9A%84%E5%9B%9B%E4%B8%AA%E7%89%B9%E6%80%A7"><span class="toc-number">3.</span> <span class="toc-text">优秀程序设计的四个特性</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3"><span class="toc-number">4.</span> <span class="toc-text">面向对象思想</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%81%E8%A3%85"><span class="toc-number">4.1.</span> <span class="toc-text">封装</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%A7%E6%89%BF%E5%92%8C%E5%A4%9A%E6%80%81"><span class="toc-number">4.2.</span> <span class="toc-text">继承和多态</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">5.</span> <span class="toc-text">总结</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%9C%E8%80%85%E7%9A%84%E8%AF%9D"><span class="toc-number">6.</span> <span class="toc-text">作者的话</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-number">7.</span> <span class="toc-text">参考资料</span></a></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/img/cover4.png')"><div id="footer-wrap"><div class="copyright">&copy;2023 - 2025 By 夜悊</div><div class="footer_custom_text"><a target="_blank" href="https://beian.miit.gov.cn/" >琼ICP备2023001225号-1</a><br><img src= "" data-lazy-src="/img/beian.png"/>&nbsp<a target="_blank" href="https://www.beian.gov.cn/portal/registerSystemInfo?recordcode=46010802001221" >琼公网安备 46010802001221号</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="translateLink" type="button" title="简繁转换">繁</button><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js?v=4.13.0"></script><script src="/js/main.js?v=4.13.0"></script><script src="/js/tw_cn.js?v=4.13.0"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui@5.0.33/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.8.8/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js?v=4.13.0"></script></div></div></body></html>